package com.gensdai.leliang.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.adapter.system_list_adapter;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.entity.Call;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.view.DeleteItmeList;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/27.
 */

public class system_call extends BaseActivityNoAbs implements View.OnClickListener {

    @BindView(R.id.ui_title)
    TextView uiTitle;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.system_list)
    DeleteItmeList systemList;
    @BindView(R.id.no_czb)
    LinearLayout noCzb;

    private List<Call> mData = new ArrayList<Call>();
    system_list_adapter madapter;
    SharedPreferences share;

    private Upload up;
    private int position = -1;
    private final int ENTER = 1;//
    private final int ALTER = 2;//
    private final int DELECT = 3;//
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            mData = (List<Call>) new json_base().JsonSystemCall(new JSONObject((String) msg.obj));
                            SetList();
                        } else {
                            Toast.makeText(
                                    system_call.this,
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case ALTER:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            Intent go;
                            if (mData.get(position).getType().equals("1") || mData.get(position).getType().equals("2")) {
                                go = new Intent(system_call.this, Get_Griytg_Gold.class);
                            } else {
                                go = new Intent(system_call.this, Get_deal.class);
                            }
                            system_call.this.startActivity(go);

                        }
                        Toast.makeText(
                                system_call.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case DELECT:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            System.out.println("" + position);
                            mData.remove(position);
                            madapter.notifyDataSetChanged();
                            systemList.turnToNormal();
                        } else {
                            Toast.makeText(
                                    system_call.this,
                                    new JSONObject((String) msg.obj)
                                            .getString("message"),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.system_news);
        ButterKnife.bind(this);
        init();

    }

    @Override
    protected void onStart() {
        super.onStart();
        Query();
    }

    /**
     * 初始化
     */
    private void init() {
        uiTitle.setText("系统消息");
        up = new Upload(this);
        back.setOnClickListener(this);
        share = getSharedPreferences("User", MODE_PRIVATE);

        //用于点击
        systemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (systemList.canClick()) {
                    alter(mData.get(position).getId());
                    system_call.this.position = position;
                }
            }
        });
    }

    /**
     * 设置list
     */
    private void SetList() {
        if (mData == null) {
//            Toast.makeText(
//                    system_call.this,
//                    "暂无数据哟，赶快去下单吧！！！",
//                    Toast.LENGTH_SHORT).show();
            noCzb.setVisibility(View.VISIBLE);
            systemList.setVisibility(View.GONE);
        } else {
            madapter = new system_list_adapter(this, mData, delete);
            systemList.setAdapter(madapter);
            noCzb.setVisibility(View.GONE);
            systemList.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            default:
                break;
        }
    }

    system_list_adapter.deleteItem delete = new system_list_adapter.deleteItem() {

        @Override
        public void delete(int position) {
            delect(mData.get(position).getId());
            system_call.this.position = position;
        }
    };


    /**
     * 删除item，并播放动画
     * @param rowView 播放动画的view
     * @param positon 要删除的item位置
     */
    protected void removeListItem(View rowView, final int positon) {

        final Animation animation = (Animation) AnimationUtils.loadAnimation(rowView.getContext(), R.anim.shanchu_itme);
        animation.setAnimationListener(new Animation.AnimationListener() {
            public void onAnimationStart(Animation animation) {}

            public void onAnimationRepeat(Animation animation) {}

            public void onAnimationEnd(Animation animation) {
                mData.remove(positon);
                madapter.notifyDataSetChanged();
                animation.cancel();
            }
        });


        rowView.startAnimation(animation);

    }


    /**
     * 查询订单消息
     */
    private void Query() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userno", share.getString("userno", ""));
        loginParams.put("noticeType", "1"); //系统消息
        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).Query_Message_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    /**
     * 订单消息改变
     */
    private void alter(String id) {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("id", id + ""); //订单id
        AlterToStr(loginParams);
    }

    //返回字符串类型
    private void AlterToStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).CHANGE_MSG_STATUS_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ALTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    /**
     * 删除消息
     */
    private void delect(String id) {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("id", id + ""); //订单id
        DeleteToStr(loginParams);
    }

    //返回字符串类型
    private void DeleteToStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).INVALID_MES_STATUS_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = DELECT;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

}
